#!/bin/bash
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
UBUNTU_VERSION=24.10
CLOUD_IMG="ubuntu-${UBUNTU_VERSION}-server-cloudimg-amd64.img"
CLOUD_IMG_PATH=$(realpath "${SCRIPT_DIR}/${CLOUD_IMG}")


download_image() {
    # Get the checksum file first
    if [[ -f ${SCRIPT_DIR}/"SHA256SUMS" ]]; then
        rm ${SCRIPT_DIR}/"SHA256SUMS"
    fi

    OFFICIAL_UBUNTU_IMAGE="https://cloud-images.ubuntu.com/releases/${UBUNTU_VERSION}/release/"
    wget "${OFFICIAL_UBUNTU_IMAGE}/SHA256SUMS" -O ${SCRIPT_DIR}/"SHA256SUMS"

    while :; do
        # Download the cloud image if not exists
        if [[ ! -f ${CLOUD_IMG_PATH} ]]; then
            wget -O ${CLOUD_IMG_PATH} ${OFFICIAL_UBUNTU_IMAGE}/${CLOUD_IMG}
        fi

        # calculate the checksum
        download_sum=$(sha256sum ${CLOUD_IMG_PATH} | awk '{print $1}')
        found=false
        while IFS= read -r line || [[ -n "$line" ]]; do
            if [[ "$line" == *"$CLOUD_IMG"* ]]; then
                if [[ "${line%% *}" != ${download_sum} ]]; then
                    echo "Invalid download file according to sha256sum, re-download"
                    rm ${CLOUD_IMG_PATH}
                else
                    ok "Verify the checksum for Ubuntu cloud image."
                    return
                fi
                found=true
            fi
        done < ${SCRIPT_DIR}/"SHA256SUMS"
        if [[ $found != "true" ]]; then
            echo "Invalid SHA256SUM file"
            exit 1
        fi
    done
}

mount_cloud_image() {
   mkdir -p /tmp/mk-image/mnt/EFI
   mkdir -p /tmp/mk-image/mnt/boot
  
   mountdev="/dev/nbd4"
   qemu-nbd -c ${mountdev} ${CLOUD_IMG} && sleep 1
   mount /dev/nbd4p15  /tmp/mk-image/mnt/EFI
   mount /dev/nbd4p13  /tmp/mk-image/mnt/boot
  
# export rootfs partition to raw file 
   dd if=/dev/nbd4p1 of=/tmp/mk-image/rootfs.raw bs=4M status=progress

}

clearn() {
   umount /tmp/mk-image/mnt/EFI
   umount /tmp/mk-image/mnt/boot

   qemu-nbd -d /dev/nbd4
}

exec_mkosi() {
   cd mkosi-config
   mkosi -ff  --debug-workspace --debug
   cd -
}

download_image

mount_cloud_image 

exec_mkosi

clearn
